package com.deli.springboot.quartz.sendMessage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.deli.springboot.controller.CommonController;
import com.deli.springboot.entity.Book;
import com.deli.springboot.entity.BorrowHistory;
import com.deli.springboot.entity.QuartzJob;
import com.deli.springboot.service.BookService;
import com.deli.springboot.service.BorrowHistoryService;
import com.deli.springboot.service.QuartzJobService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Quartz设置项目全局的定时任务
 */

public class SendMessageJob implements Job {
    private static final Logger logger = LoggerFactory.getLogger(SendMessageJob.class);

    @Autowired
    private CommonController commonController;
    @Autowired
    private BorrowHistoryService borrowHistoryService;
    @Autowired
    private BookService bookService;
    @Autowired
    private QuartzJobService quartzJobService;

    @Scheduled(cron = "0/2 * * * * ? *")//每5秒执行一次
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        BorrowHistory borrowHistory = new BorrowHistory();
        borrowHistory.setStatus(1);
        List<BorrowHistory> borrowHistories = borrowHistoryService.findByExample(borrowHistory);

        for (BorrowHistory history : borrowHistories) {
            long bDatetimes = history.getbDate().getTime();
            long nowDatetimes = new Date().getTime();
            int day = (int) ((nowDatetimes - bDatetimes) / 86400000);
            if (day == 7 || day == 3 || day == 1) {
                //调用接口，发送消息
                String accessToken = commonController.getToken();
                String strURL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
                String touser = history.getUserId().toString();

                HashMap<String, Object> params = new HashMap<>();
                params.put("touser", touser);
                params.put("msgtype", "text");
                HashMap<String, String> text = new HashMap<>();

                //书名
                Book book = new Book();
                book.setId(history.getBookId());
                List<Book> books = bookService.findByExample(book);
                String bookName = books.get(0).getbName();

                //日期
                Format f = new SimpleDateFormat("yyyy-MM-dd");
                Date bDate = history.getbDate();
                f.format(bDate);
                Calendar c = Calendar.getInstance();
                c.setTime(bDate);
                c.add(Calendar.DAY_OF_MONTH, 30);// bDate+30天

                text.put("content", "您借阅的【" + bookName + "】还有【" + day + "】天到期，请您抓紧日期阅读，并于【" + c.getTime() + "】按时归还。");
                params.put("text", text);
                String paramString = JSON.toJSONString(params);
                try {
                    URL url = new URL(strURL);// 创建连接
                    HttpURLConnection connection = (HttpURLConnection) url
                            .openConnection();
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.setUseCaches(false);
                    connection.setInstanceFollowRedirects(true);
                    connection.setRequestMethod("POST"); // 设置请求方式
                    connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
                    connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
                    connection.connect();
                    OutputStreamWriter out = new OutputStreamWriter(
                            connection.getOutputStream(), "UTF-8"); // utf-8编码
                    out.append(paramString);
                    out.flush();
                    out.close();
                    // 读取响应
                    int length = connection.getContentLength();// 获取长度
                    InputStream is = connection.getInputStream();
                    if (length != -1) {
                        byte[] data = new byte[length];
                        byte[] temp = new byte[512];
                        int readLen = 0;
                        int destPos = 0;
                        while ((readLen = is.read(temp)) > 0) {
                            System.arraycopy(temp, 0, data, destPos, readLen);
                            destPos += readLen;
                        }
                        String result = new String(data, "UTF-8"); // utf-8编码

                        //获取发送结果
                        JSONObject jsonObject = JSON.parseObject(result);
                        QuartzJob quartzJob = new QuartzJob();
                        quartzJob.setMessageContext(text.get("content"));
                        quartzJob.setBorrowHistoryId(history.getId());
                        if (jsonObject.getInteger("errcode") == 0) {
                            //发送成功
                            quartzJob.setStatus(0);
                        } else {
                            //发送失败
                            quartzJob.setStatus(1);
                            quartzJob.setExceptionInfo(jsonObject.getString("errmsg"));
                        }
                        quartzJobService.addRecord(quartzJob);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("An exception occurs when a timing task is executed ，" + new Date());
                }
            }
        }
    }

}
